/*
 * Copyright 2008-2009 Aying.Net with Fuchun. 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.aying.ubb;

import java.util.Map;
import java.util.HashMap;
import java.util.Collections;

/**
 * 包含基本 <code>UBB</code> 代码值作为常用静态方法的工具类。
 * 
 * @author Fuchun
 * @version 1.0, 2009-6-3
 */
public class UBBUtils {

    // 用于保存查找 UBB 代码的正则表达式的 Cache Map
    private static Map<String, String> cacheUBBRegexs = Collections
            .synchronizedMap(new HashMap<String, String>());

    /**
     * 通过 <code>UBB</code> 标签的名称获得查找该标签的正则表达式字符串。
     * 
     * @param ubbCode 要获得的 <code>UBB</code> 标签的名称。
     * @return 字符串形式的正则表达式。如果指定的 <code>UBB</code> 标签的名称未找到，则返回空字符串。
     */
    public static String getRegex(String ubbCode) {
        if (ubbCode == null || "".equals(ubbCode.trim()))
            return "";
        ubbCode = ubbCode.trim().toLowerCase();
        if (cacheUBBRegexs.containsKey(ubbCode))
            return cacheUBBRegexs.get(ubbCode);
        char[] chars = ubbCode.toCharArray();
        StringBuffer buffer = new StringBuffer();
        buffer.append("\\[");
        for(char c : chars) {
            buffer.append("[").append(String.valueOf(c).toLowerCase());
            buffer.append(String.valueOf(c).toUpperCase()).append("]");
        }
        buffer.append("[=]?([^\\]]*)\\](.*?)\\[\\/");
        for(char c : chars) {
            buffer.append("[").append(String.valueOf(c).toLowerCase());
            buffer.append(String.valueOf(c).toUpperCase()).append("]");
        }
        buffer.append("\\]");
        cacheUBBRegexs.put(ubbCode, buffer.toString());
        return buffer.toString();
    }
}
